<template>
  <div class="mapContainer">
    <div id="map" ref="Map"></div>
    <div class="tools">
    </div>
  </div>
</template>

<script>
import L from "leaflet"
import 'leaflet.pm'
var esri = require("esri-leaflet");
export default {
  name: 'Maps',
  components: {
  },
  data () {
    return {
      map: null,
      mapDOM:null,
      tiandituToken: 'e79bd7f79e49dbdd15eb24aca1fcb9ea',
      tiledLayer:null,
      tiledLayerAnno: null,
      imgtiledLayer: null,
      imgtiledLayerAnno: null,
      tileLayerGroup: null,
      imgLayerGroup: null,
      position:null ,
      pointsLayerGroup:null, 
      taskpointsLayerGroup:null,  
      testpoints:[
        {lat:32.090, lng:118.875 ,state:3 },
        {lat:32.095, lng:118.888 ,state:3 },
        {lat:32.099, lng:118.864 ,state:3 },
      ],
      taskPoints:[
         {lat:32.093, lng:118.875 ,state:0 },
        {lat:32.073, lng:118.888 ,state:1 },
        {lat:32.077, lng:118.864 ,state:2 },
      ]
    }
  },
  created () { },
  mounted () {
    this.$nextTick(() => {
      //矢量底图
      this.tiledLayer = L.tileLayer("http://t0.tianditu.com/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk={token}", {
        maxZoom: 18,
        tileSize: 256,
        zoomOffset: 1,
        zIndex: 1,
        token: this.tiandituToken
      });
      //矢量注记
      this.tiledLayerAnno = L.tileLayer("http://t0.tianditu.com/cva_c/wmts?layer=cva&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk={token}", {
        maxZoom: 18,
        tileSize: 256,
        zoomOffset: 1,
        zIndex: 1,
        token: this.tiandituToken
      });
      //影像底图
      this.imgtiledLayer = L.tileLayer("http://t0.tianditu.com/img_c/wmts?layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk={token}", {
        maxZoom: 18,
        tileSize: 256,
        zoomOffset: 1,
        zIndex: 1,
        token: this.tiandituToken
      });
      //影像注记
      this.imgtiledLayerAnno = L.tileLayer("http://t0.tianditu.com/cia_c/wmts?layer=cia&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk={token}", {
        maxZoom: 18,
        tileSize: 256,
        zoomOffset: 1,
        zIndex: 1,
        token: this.tiandituToken
      });
      this.map = L.map('map', {
        crs: L.CRS.EPSG4326,
        center: [32.090704575798206, 118.87560894821435],
        zoom: 10,
        maxZoom: 17,
        zoomControl: true,
      });
       esri.dynamicMapLayer({
            url: 'http://demo.njzhxt.com:16080/arcgis/rest/services/fpsp/fpsp_czjx/MapServer',
            zIndex: 7,
            useCors: true,
          }).addTo(this.map)
           esri.dynamicMapLayer({
            url: 'http://demo.njzhxt.com:16080/arcgis/rest/services/fpsp/fpsp_fdxgdjx/MapServer',
            zIndex: 5,
            useCors: true,
          }).addTo(this.map)
            esri.dynamicMapLayer({
            url: 'http://demo.njzhxt.com:16080/arcgis/rest/services/fpsp/fpsp_fdxjbntbhq/MapServer',
            zIndex: 6,
            useCors: true,
          }).addTo(this.map)

        esri.query({
        url: "http://192.168.6.211:6080/arcgis/rest/services/TRPC/MapServer/0",
        useCors: true
      }).run((error, result) => {
        console.log(result.features);
      })

        this.map.pm.addControls({ 
          position: 'topleft', 
          drawCircle: true, 
          drawMarker:true, 
          drawCircleMarker:true, 
          drawPolyline:true, 
          drawRectangle:true, 
          drawPolygon:true, 
          cutPolygon:true, 
          removalMode:true, 
          editMode:true, 
          dragMode:true 
  }); 
      //构建完成地图实例之后，将其传给父组件
      this.emitToParent();
      this.tileLayerGroup = L.layerGroup([this.tiledLayer, this.tiledLayerAnno]);
      this.imgLayerGroup = L.layerGroup([this.imgtiledLayer, this.imgtiledLayerAnno]);
      this.imgLayerGroup.addTo(this.map);
      this.mapDOM=document.getElementById('map');
      // this.getlatIng()
      this.loadtaskPoints()
      this.loadPoints()
    })
  },
  watch: {},
  computed: {},
  methods: {
    emitToParent(){
       this.$emit('child-map',this.map)
    },
      getlatIng(){
          var mypop = L.popup();
          this.map.on('click',(e)=>{
            var content = '你临幸了这个点：<br>';
            content += e.latlng.toString();
            mypop.setLatLng(e.latlng)
                 .setContent(content)
                 .openOn(this.map);
                 console.log(e.latlng);
                 this.position=e.latlng;
                 console.log(this.position);
         });
    },
       //加载任务点
    loadtaskPoints(){
       var userIcon = L.icon({
        iconUrl:'user.png',
        iconSize: [20, 20],
        // iconAnchor: [13, 21]
        })
       var blueIcon = L.icon({
        iconUrl:'blue.png',
        iconSize: [20, 20],
        // iconAnchor: [13, 21]
        })
         var redIcon = L.icon({
        iconUrl:'red.png',
        iconSize: [20, 20],
        // iconAnchor: [13, 21]
        })
         var greenIcon = L.icon({
        iconUrl:'green.png',
        iconSize: [20, 20],
        // iconAnchor: [13, 21]
        })
      let points=this.taskPoints.map(item=>{
      return {
        lat:item.lat,
        lng:item.lng,
        state: item.state===0 ?'已完成':item.state===1 ?'未完成':item.state ===2?'正在进行':'规划点'
       }
     })
      this.taskpointsLayerGroup = L.layerGroup().addTo(this.map)  
     for(let i=0;i<points.length;i++){
        let lat = points[i].lat
        let lng = points[i].lng
          L.marker([lat, lng],{
        icon:points[i].state ==='已完成' ? blueIcon:points[i].state ==='未完成' ? redIcon:points[i].state==='正在进行' ? greenIcon:userIcon,
        draggable:true,
        riseOnHover:true
      }).addTo(this.taskpointsLayerGroup).bindPopup(`<div>状态:${points[i].state}</div>
                                                       <button>定位</button>
                                                       <button>导航</button>`)
     }
    },
    //加载规划点以及任务围栏
    loadPoints(){
        var userIcon = L.icon({
        iconUrl:'user.png',
        iconSize: [20, 20],
        // iconAnchor: [13, 21]
        })
        var blueIcon = L.icon({
        iconUrl:'blue.png',
        iconSize: [20, 20],
        // iconAnchor: [13, 21]
        })
         var redIcon = L.icon({
        iconUrl:'red.png',
        iconSize: [20, 20],
        // iconAnchor: [13, 21]
        })
         var greenIcon = L.icon({
        iconUrl:'green.png',
        iconSize: [20, 20],
        // iconAnchor: [13, 21]
        })
      let points=this.testpoints.map(item=>{
      return {
        lat:item.lat,
        lng:item.lng,
        state: item.state===0 ?'已完成':item.state===1 ?'未完成':item.state ===2?'正在进行':'规划点'
       }
     })
     console.log(points);
        //存放电子围栏以及规划点位
         this.pointsLayerGroup = L.layerGroup() 
         //实例化一个图层 单独存放不需要展示的圆形 获取边界后 清除LayerGroup
         var circleLayer= L.layerGroup().addTo(this.map)
          for (let i = 0; i <points.length; i++) {
        let lat = points[i].lat
        let lng = points[i].lng
        let circlePoints=L.circle([lat,lng],500).addTo(circleLayer)
        let bounds=[
          [circlePoints.getBounds()._northEast.lat,circlePoints.getBounds()._northEast.lng],
          [circlePoints.getBounds()._southWest.lat,circlePoints.getBounds()._southWest.lng]
        ]
          console.log(bounds);
          circleLayer.clearLayers()
        var latlngs=  L.rectangle(bounds, {color: "#ff7800", weight: 1})
        latlngs.addTo(this.pointsLayerGroup);
        L.marker([lat, lng],{
        icon:points[i].state ==='已完成' ? blueIcon:points[i].state ==='未完成' ? redIcon:points[i].state==='正在进行' ? greenIcon:userIcon,
        // draggable:true,
        // riseOnHover:true
      }).addTo(this.pointsLayerGroup).bindPopup(`状态:${points[i].state}`)
    }   

     this.map.on('zoomend', (e) => {
    //获取当前放大或者缩小的等级
    let zoom = e.target.getZoom();
            // console.log(zoom);
            if (zoom >= 13) {
                this.map.addLayer(this.pointsLayerGroup);
            }
            else if (zoom <13) {
                this.map.removeLayer(this.pointsLayerGroup);                
            } 

}); 
  },
  //判断当前位置是否在电子围栏内
  // pointInFence(point,bounds){
           
  // }
}
}
</script>
<style lang="scss" scoped>
.mapContainer {
  width: 100%;
  height: 100%;
  position: relative;
}
.tools{
  position: absolute;
  z-index: 2;
  top: -5%;
  right: 2%;
}
#map {
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 100%;
}
</style>